package cn.uyunsky.platform.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.uyunsky.platform.controller.ControllerTool;
import cn.uyunsky.platform.data.UDataTool;
import cn.uyunsky.platform.data.UData;
import cn.uyunsky.platform.data.UHead;
import cn.uyunsky.platform.service.ServiceExecute;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.uyunsky.platform.BeanFactoryUtil;
import cn.uyunsky.platform.exception.PLException;
import cn.uyunsky.platform.util.PL;

/**
 * <p>
 * Description: 处理异步的request请求,请求内容为JSON;靠前端正确处理数据类型了
 * <p>
 * 使用JSON好处是统一了数据格式,并且强制了数据类型,并且可以有<b>结构</b>和<b>数组</b>形式的数据
 * </p>
 * </p>
 *
 * @author baiyh
 * @version 1.0
 */
public class ServiceDispacth extends HttpServlet {
    private static Log log = LogFactory.getLog(ServiceDispacth.class);
    private static final long serialVersionUID = 1L;
    private static final int buffsize = 1024;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //不支持GET提交
        ServletUtil.wirteJSONObj(UDataTool.createResult(false, UDataTool.ERROR_CODE, UDataTool.ERROR_MSG), resp);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String uri = request.getRequestURI();
            String service = uri.substring(uri.lastIndexOf("/") + 1, uri.indexOf("."));

            ServletInputStream in = request.getInputStream();

            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[buffsize]; //buff用于存放循环读取的临时数据
            int rc = 0;
            while ((rc = in.read(buff, 0, buffsize)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] requestBuff = swapStream.toByteArray();
            String json = new String(requestBuff, "UTF-8");
            if (log.isInfoEnabled())
                log.info("请求JSON数据:" + json);

            Map reqdata = PL.JSON.fromJSON(json);

            UHead head = new UHead();
            head.setService(service);
            setUserInfo(request, head);

            // 执行服务
            UData data = new UData();
            data.setHead(head);
            data.setBody(reqdata);
            data.setJson(json);

            if (log.isInfoEnabled())
                log.info("请求数据为:" + data);

            ServiceExecute execute = (ServiceExecute) BeanFactoryUtil.getBean("serviceExecute");
            UData resData = execute.execute(service, data);

            if (log.isInfoEnabled())
                log.info("响应数据为:" + resData);

            ServletUtil.wirteJSONObj(resData, resp);
        } catch (PLException e) {
            log.error("服务执行业务错误", e);
            ServletUtil.wirteJSONObj(UDataTool.createResult(false, e.getKey(), e.getMessage()), resp);
        } catch (Exception e) {
            log.error("服务执行异常", e);
            ServletUtil.wirteJSONObj(UDataTool.createResult(false, UDataTool.ERROR_CODE, UDataTool.ERROR_MSG), resp);
        }

    }


    private void setUserInfo(HttpServletRequest req, UHead head) {
        head.setUserid(ControllerTool.getUseridBySession(req.getSession()));
    }

}
